package servlet;

import entity.User;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 石小俊
 * @date 2023年11月02日 15:54
 */
@WebServlet("*.user")
public class UserServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String path = request.getServletPath();
        switch (path){
            case "/findAll.user":
                findAll(request,response);
                break;
            case "/findById.user":
                findById(request,response);
                break;
        }
    }

    protected void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/shop?useUnicode=true&characterEncoding=utf-8";
        List<User> users = new ArrayList<>();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,"root","");
            String sql = new StringBuffer()
                    .append(" select id,username,password,phone,address ")
                    .append(" from t_user ")
                    .toString();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()){
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                users.add(user);
            }
            request.setAttribute("users",users);
            request.getRequestDispatcher("/jquery/list.jsp").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void findById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String id = request.getParameter("id");
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/shop?useUnicode=true&characterEncoding=utf-8";
        User user = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,"root","");
            String sql = new StringBuffer()
                    .append(" select id,username,password,phone,address ")
                    .append(" from t_user ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1,Integer.parseInt(id));
            rs = ps.executeQuery();
            if(rs.next()){
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));

                // 此时后台已经查询出对应的用户信息
                // Java与js两者的对象概念是不一样的
                // 如何将Java中查询出来的对象数据传递到前台的js中?
                // Java与js均支持字符串
                // 可以在此时将一个Java对象以JSON格式的字符串进行输出
                // 前台js获取到JSON格式的字符串之后再将其转换成js中的对象进行处理
                // out.println("{'id':"+user.getId()+",'username':'"+user.getUsername()+"','password':'"+user.getPassword()+"','phone':'"+user.getPhone()+"','address':'"+user.getAddress()+"'}");

                // 可以使用JSON工具类将一个Java对象转换成JSON对象
                JSONObject jsonObject = JSONObject.fromObject(user);
                // 在JSON对象中提供了转换成JSON格式字符串的方法
                // 此时输出时在js中接收到的已经是字符串了,说明自动进行了转换
                // out.print(jsonObject);
                // 但是其本质上并不是字符串,在该对象中提供了toString方法将JSON对象转换成JSON格式的字符串
                String userJson = jsonObject.toString();
                out.print(userJson);

                // 如果后台查询的数据是一个集合
                // List<User> users = new ArrayList<>();
                // 此时可以通过JSONArray进行操作
                // 该对象表示一个JSON数组,用法与JSONObject一致
                // JSONArray userArray = JSONArray.fromObject(users);
                // out.print(userArray.toString());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
